'use client';

import { useEffect, useState, useCallback } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { ArrowLeftOutlined } from '@ant-design/icons';

interface FloatingBackButtonProps {
  className?: string;
  size?: number;
  color?: string;
  backgroundColor?: string;
  shadowColor?: string;
  position?: 'left' | 'right';
  topOffset?: number;
  showOnDesktop?: boolean;
  customIcon?: React.ReactNode;
  hideOnAdminPages?: boolean;
  adminPageBehavior?: 'hide' | 'custom' | 'default';
}

export default function FloatingBackButton({
  className = '',
  size = 48,
  color = '#ffffff',
  backgroundColor = '#1890ff',
  shadowColor = 'rgba(0, 0, 0, 0.15)',
  position = 'right',
  topOffset = 0,
  showOnDesktop = false,
  customIcon,
  hideOnAdminPages = true,
  adminPageBehavior = 'hide'
}: FloatingBackButtonProps) {
  const [isVisible, setIsVisible] = useState(false);
  const [isPressed, setIsPressed] = useState(false);
  const router = useRouter();
  const pathname = usePathname();

  // 检测是否为移动端
  const checkMobile = useCallback(() => {
    const mobile = window.innerWidth <= 768;
    setIsVisible(mobile || showOnDesktop);
  }, [showOnDesktop]);

  // 检测是否为管理后台页面
  const isAdminPage = pathname?.startsWith('/admin');

  useEffect(() => {
    checkMobile();
    window.addEventListener('resize', checkMobile);

    return () => window.removeEventListener('resize', checkMobile);
  }, [checkMobile]);

  // 返回上一页
  const handleBack = useCallback(() => {
    if (isAdminPage && adminPageBehavior === 'custom') {
      // 在管理后台页面，返回上一级管理页面
      if (pathname?.includes('/edit')) {
        // 编辑页面返回列表页
        const basePath = pathname.split('/').slice(0, -1).join('/');
        router.push(basePath);
      } else {
        // 其他页面返回仪表盘
        router.push('/admin/dashboard');
      }
    } else if (window.history.length > 1) {
      router.back();
    } else {
      // 如果没有历史记录，跳转首页
      router.push('/');
    }
  }, [router, isAdminPage, adminPageBehavior, pathname]);

  // 触摸事件处理
  const handleTouchStart = useCallback(() => {
    setIsPressed(true);
  }, []);

  const handleTouchEnd = useCallback(() => {
    setIsPressed(false);
  }, []);

  // 根据配置决定是否显示
  if (!isVisible || (hideOnAdminPages && isAdminPage && adminPageBehavior === 'hide')) {
    return null;
  }

  const buttonStyle = {
    position: 'fixed' as const,
    ...(position === 'left' ? { left: '20px' } : { right: '20px' }),
    top: `calc(70% + ${topOffset}px)`,
    transform: `translateY(-50%) scale(${isPressed ? 0.95 : 1})`,
    width: `${size}px`,
    height: `${size}px`,
    borderRadius: '50%',
    backgroundColor,
    color,
    border: 'none',
    cursor: 'pointer',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    boxShadow: `0 4px 12px ${shadowColor}`,
    zIndex: 1000,
    transition: 'all 0.2s cubic-bezier(0.4, 0, 0.2, 1)',
    fontSize: `${size * 0.4}px`,
    userSelect: 'none' as const,
    WebkitTapHighlightColor: 'transparent',
  };

  return (
    <button
      onClick={handleBack}
      className={`floating-back-button ${className}`}
      style={buttonStyle}
      onTouchStart={handleTouchStart}
      onTouchEnd={handleTouchEnd}
      onMouseEnter={(e) => {
        if (!isPressed) {
          e.currentTarget.style.transform = `translateY(-50%) scale(1.1)`;
          e.currentTarget.style.boxShadow = `0 6px 20px ${shadowColor}`;
        }
      }}
      onMouseLeave={(e) => {
        if (!isPressed) {
          e.currentTarget.style.transform = `translateY(-50%) scale(1)`;
          e.currentTarget.style.boxShadow = `0 4px 12px ${shadowColor}`;
        }
      }}
      aria-label={isAdminPage ? "返回管理页面" : "返回上一页"}
      title={isAdminPage ? "返回管理页面" : "返回上一页"}
    >
      {customIcon || <ArrowLeftOutlined />}
    </button>
  );
}
